package com.itheima.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisMakeIds {

    private static final Long REMOVE = 32L;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long makeIds(String keyPrefix){
        //获取当前时间戳
        LocalDateTime beginTime = LocalDateTime.of(2000, 1, 1, 0, 0, 0);
        long beginTimeEpochSecond = beginTime.toEpochSecond(ZoneOffset.UTC);
        LocalDateTime endTime = LocalDateTime.now();
        long endTimeEpochSecond = endTime.toEpochSecond(ZoneOffset.UTC);
        long time = endTimeEpochSecond - beginTimeEpochSecond;
        //利用redis的自增，获取编号
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy:MM:dd");
        String format = endTime.format(dateTimeFormatter);
        String key = "incr" + keyPrefix + format;
        Long increment = stringRedisTemplate.opsForValue().increment(key);
        //返回订单编号
        return time << REMOVE | increment;
    }

}
